import { ElMessage } from 'element-plus'

/**
 * Vue权限指令
 * 使用方法: v-permission="'permission:code'"
 */
export default {
  mounted(el, binding) {
    const { value } = binding
    
    if (!value) {
      return
    }
    
    // 从localStorage获取用户权限信息
    const userInfo = localStorage.getItem('userInfo')
    if (!userInfo) {
      el.style.display = 'none'
      return
    }
    
    try {
      const user = JSON.parse(userInfo)
      const userPermissions = user.permissions || []
      
      // 检查用户是否有指定权限
      if (!userPermissions.includes(value)) {
        el.style.display = 'none'
      }
    } catch (error) {
      console.error('解析用户权限信息失败:', error)
      el.style.display = 'none'
    }
  },
  
  updated(el, binding) {
    const { value } = binding
    
    if (!value) {
      return
    }
    
    // 从localStorage获取用户权限信息
    const userInfo = localStorage.getItem('userInfo')
    if (!userInfo) {
      el.style.display = 'none'
      return
    }
    
    try {
      const user = JSON.parse(userInfo)
      const userPermissions = user.permissions || []
      
      // 检查用户是否有指定权限
      if (!userPermissions.includes(value)) {
        el.style.display = 'none'
      } else {
        el.style.display = ''
      }
    } catch (error) {
      console.error('解析用户权限信息失败:', error)
      el.style.display = 'none'
    }
  }
}

/**
 * 权限检查函数
 * @param {string} permission - 权限代码
 * @returns {boolean} - 是否有权限
 */
export function hasPermission(permission) {
  if (!permission) {
    return true
  }
  
  const userInfo = localStorage.getItem('userInfo')
  if (!userInfo) {
    return false
  }
  
  try {
    const user = JSON.parse(userInfo)
    const userPermissions = user.permissions || []
    return userPermissions.includes(permission)
  } catch (error) {
    console.error('解析用户权限信息失败:', error)
    return false
  }
}

/**
 * 显示权限不足提示
 */
export function showPermissionDenied() {
  ElMessage.warning('您没有权限执行此操作，请联系管理员')
}
